import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ProductAttrApiService } from 'src/app/api/product-attr-api.service';
import { ProductAttributeCateServiceApi } from 'src/app/api/product-attribute-cate-api.service';
import { ProductAttribute } from 'src/app/model/productAttr';

@Component({
  selector: 'app-product-attr-detail',
  templateUrl: './product-attr-detail.component.html',
  styleUrls: ['./product-attr-detail.component.less', '../../../../styles/container.css']
})
export class ProductAttrDetailComponent implements OnInit, OnChanges {

  @Input() productAttr: ProductAttribute;
  attrForm: FormGroup;
  attrCateOptions = new Array<{ label: string, value: number }>();
  cid: number;
  type: number;

  constructor(
    private fb: FormBuilder,
    private attrApi: ProductAttrApiService,
    private cateApi: ProductAttributeCateServiceApi,
    private route: ActivatedRoute,
    private message: NzMessageService,
  ) {
    this.attrForm = this.fb.group({
      name: [null, [Validators.required]],
      productAttributeCategoryId: [0],
      filterType: [0],
      searchType: [0],
      relatedStatus: [0],
      selectType: [0],
      inputType: [0],
      inputList: [''],
      handAddStatus: [0],
      sort: [0, [Validators.pattern('[0-9]*')]],
      type: [null]
    })
  }

  ngOnChanges(changes: SimpleChanges): void {
    const curAttrValue = changes['productAttr'].currentValue;
    this.setFormValue(curAttrValue)
  }

  ngOnInit(): void {
    this.fetchAttrCateFromServer();
    this.route.queryParams.subscribe(
      param => {
        if (param.cid) {
          this.cid = Number.parseInt(param.cid, 10);
          this.attrForm.get('productAttributeCategoryId').setValue(this.cid)
        }
        if (param.type) {
          this.type = Number.parseInt(param.type, 10);
          this.attrForm.get('type').setValue(this.type)
        }
      },
    )
  }

  submitForm() {
    for (const key in this.attrForm.controls) {
      this.attrForm.get(key).markAsDirty();
      this.attrForm.get(key).updateValueAndValidity();
    }
    if (this.attrForm.valid) {
      let submitData = this.attrForm.value;
      const inputList: string = submitData.inputList;
      if (inputList) {
        let inputArray: string[] = inputList.split(`\n`).map(item => item.trim());
        submitData.inputList = inputArray.toString()
      }
      if (this.productAttr?.id) {
        this.updateAttr(submitData);
      } else {
        this.createAttr(submitData);
      }
    }
  }

  handleReset = () => {
    this.attrForm.reset(
      {
        productAttributeCategoryId: 0,
        selectType: 0,
        inputType: 0,
        inputList: '',
        sort: 0,
        filterType: 0,
        searchType: 0,
        relatedStatus: 0,
        handAddStatus: 0,
        type: null,
        name: null,
      }
    );
    this.attrForm.get('productAttributeCategoryId').setValue(this.cid);
    this.attrForm.get('type').setValue(this.type);
    this.attrForm.get('sort').setValue(0);
  }

  private setFormValue(source: ProductAttribute) {
    this.attrForm.setValue({
      productAttributeCategoryId: source.productAttributeCategoryId,
      selectType: source.selectType,
      inputType: source.inputType,
      inputList: source.inputList ? source.inputList.replace(/,/g, `\n`) : null,
      sort: source.sort,
      filterType: source.filterType,
      searchType: source.searchType,
      relatedStatus: source.relatedStatus,
      handAddStatus: source.handAddStatus,
      type: source.type,
      name: source.name,
    });
  }

  private fetchAttrCateFromServer() {
    this.cateApi.listAll().subscribe(
      cates => this.attrCateOptions = cates.map(cate => { return { label: cate.name, value: cate.id } }),
      err => console.log(err),
    )
  }

  private createAttr(data: ProductAttribute) {
    this.attrApi.create(data).subscribe(
      item => {
        this.message.success('创建成功');
        setTimeout(this.handleReset, 500);
      },
      err => {
        this.message.error('创建错误');
        console.error(err);
      }
    )
  }

  private updateAttr(data: ProductAttribute) {
    this.attrApi.update(this.productAttr.id, data).subscribe(
      item => {
        this.message.success('编辑成功');
      },
      err => {
        this.message.error('编辑错误');
        console.error(err);
      }
    )
  }

}
